<!DOCTYPE html>
<html>
	<head>
        <meta charset="utf-8">
        <style>
            canvas {
                border: 2px solid rgb(250, 215, 215);
                background-color: aquamarine;
            }
        </style>
    </head>
    <body>
        <canvas id="myCanvas" width="750" height="700"></canvas>
        <script src="ball_animation.js"></script>
    </body>
    <script>
        (function(){
            /*
                生成一个运动的小球，规则如下:
                1.球的半径为100px,背景色随机
                2.球在x,y轴上的初速度均为10px/s
                3.撞击浏览器边缘后自动反弹
                4.鼠标左键按下球的时候球禁止，放开的时候速度+1
                5.鼠标右键按下球的时候球禁止，放开的时候速度-1
            */
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');

            class Ball {
                constructor(x, y, radius, color) {
                    this.x = x;
                    this.y = y;
                    this.radius = radius;
                    this.color = color;
                    this.dx = 10;
                    this.dy = 10;
                    this.speed = 10;
                }

                draw() {
                    ctx.beginPath();
                    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
                    ctx.fillStyle = this.color;
                    ctx.fill();
                    ctx.closePath();
                }

                update() {
                    if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
                        this.dx = -this.dx;
                    }
                    if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
                        this.dy = -this.dy;
                    }
                    this.x += this.dx;
                    this.y += this.dy;
                    this.draw();
                }
            }

            const ball = new Ball(100, 100, 100, `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`);

            function animate() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ball.update();
                requestAnimationFrame(animate);
            }

            animate();

            canvas.addEventListener('mousedown', (e) => {
                if (e.button === 0) {
                    ball.dx = 0;
                    ball.dy = 0;
                }
                 else if (e.button === 2) {
                    ball.speed -= 1;
                    ball.dx = ball.speed;
                    ball.dy = ball.speed;
                }
            });

            canvas.addEventListener('mouseup', (e) => {
                if (e.button === 0) {
                    ball.speed += 1;
                    ball.dx = ball.speed;
                    ball.dy = ball.speed;
                }
            });
        })()
    </script>
</html>